import { app, BrowserWindow, ipcMain, dialog, session, shell } from 'electron/main'
import * as chromeLauncher from 'chrome-launcher';
import * as puppeteer from 'puppeteer-core';
import * as playwright from 'playwright';
import fs from 'fs';
import path from 'path';
import os from 'os';
import { exec } from 'child_process';
// const os = require('os')
// const { exec } = require('child_process')

const openNewView = async (data) => {
    try {
        const setting = data.setting;

        // 配置代理参数
        const proxyOptions = {};
        if (data.proxy.type !== '-1') {
            proxyOptions.server = `${data.proxy.type}://${data.proxy.host}:${data.proxy.port}`;
            if (data.proxy.username) {
                proxyOptions.username = data.proxy.username;
                proxyOptions.password = data.proxy.password;
            }
        }

        // 启动 Chromium
        let browser = await playwright.chromium.launch({
            startingUrl: 'https://your-website.com',
            executablePath: data.path,
            headless: false, // 显式声明非无头模式
            proxy: Object.keys(proxyOptions).length > 0 ? proxyOptions : undefined,
            args: [
                '--ignore-certificate-errors' // 忽略证书错误
            ],
            timeout: 60000 // 启动超时时间
        }).catch(err => {
            throw new Error(`Chromium 启动失败: ${err.message}`);
        });

        // 创建浏览器上下文（支持多环境隔离）
        const context = await browser.newContext({
            userAgent: setting.userAgent,
            viewport: null // 禁用默认 viewport
        });

        // 监听页面创建事件
        context.on('page', async (page) => {
            // 配置每个新页面
            await page.route('**/*', route => route.continue()) // 自动继续所有请求
                .catch(err => console.error('路由拦截失败:', err));
        });

        // 创建新页面并导航
        // const page = await context.newPage();
        // await page.goto(data.url, {
        //     waitUntil: 'networkidle',
        //     timeout: 60000
        // }).catch(err => {
        //     throw new Error(`页面导航失败: ${err.message}`);
        // });

        // 自动处理代理认证（playwright 内置支持）
        if (proxyOptions.username) {
            page.on('request', async request => {
                if (request.url().startsWith(proxyOptions.server)) {
                    await request.authenticate({
                        username: proxyOptions.username,
                        password: proxyOptions.password
                    });
                }
            });
        }

        return { browser, context }; // 返回控制句柄

    } catch (error) {
        console.error('设备模拟失败:', error);
        if (browser) await browser.close(); // 确保异常时关闭浏览器
        throw error;
    }

}

export default openNewView;